package zb.WX.action.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import zb.WX.bean.web.UserInfo;
import zb.WX.service.web.TargetService;
import zb.WX.util.GlobalVar;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Author: BinZhang
 * @Date: 2018/6/22 0:19
 * @Description:用户手动授权引导页面
 */
@Controller
@RequestMapping("wxOAuth")
public class WxOAuthAction {
    @Autowired
    private TargetService targetService;

    /**
     * @Author: BinZhang
     * @Date: 2018/6/22 0:40
     * @Description:进入授权引导页面
     */
    @RequestMapping("/guide")
    protected void guide(HttpServletResponse response) throws IOException {
        String redirect_uri = URLEncoder.encode(GlobalVar.REDIRECT_URI, "UTF-8");
        String strUrl = GlobalVar.AUTHORIZE_URL
                .replace("APPID", GlobalVar.APPID)
                .replace("REDIRECT_URI", redirect_uri)
                .replace("SCOPE", GlobalVar.SNSAPI_USERINFO);
        response.sendRedirect(strUrl);
    }

    /**
     * @Author: BinZhang
     * @Date: 2018/6/22 0:40
     * @Description:获取用户openId、头像等信息
     */
    @RequestMapping(value = "/target", produces = "text/html;charset=UTF-8")
    protected String target(HttpSession session, String code) {
        session.setAttribute("wxCode", code);
        return "/wx/wxUserInfo";
    }

    /**
     * @Author: BinZhang
     * @Date: 2018/8/25 0:04
     * @Description:获取用户信息
     */
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public UserInfo getUserInfo(HttpSession session) {
        UserInfo userInfo = new UserInfo();
        Object wxCode = session.getAttribute("wxCode");
        if (wxCode == null) {
            return userInfo;
        }
        Object obj = session.getAttribute("wxUserInfo");
        if (obj != null) {
            return (UserInfo) obj;
        } else {
            userInfo = targetService.getUserInfo((String) wxCode);
            session.setAttribute("wxUserInfo", userInfo);
        }
        return userInfo;
    }
}
